﻿package game.breeze.socket.connection;

import game.breeze.socket.TcpSocket;
import game.breeze.socket.util.BufferWrapper;
import game.breeze.socket.util.ByteBufferWrapper;

import java.nio.channels.SocketChannel;

public class SimpleConnection extends NetConnection {
	private byte[] bufferData;

	private TcpSocket socket;

	public SimpleConnection(TcpSocket conn) {
		this(conn, new ByteBufferWrapper(), 128);
	}

	public SimpleConnection(TcpSocket conn, BufferWrapper buffer, int bufferSize) {
		super(buffer);
		socket = conn;
		bufferData = new byte[bufferSize];

		info = new ConnectionInfo(conn.getHost(), conn.getPort(), conn.getLocalPort());
	}

	protected void sendDataImpl(byte[] data, int offset, int count) {
		if (!isActive())
			return;
		socket.send(data, offset, count);
		idleTime = 0;
	}

	public TcpSocket getSocket() {
		return socket;
	}

	public void close() {
		socket.close();
	}

	public String getIP() {
		return null;
	}

	public boolean isActive() {
		return socket.active();
	}

	public SocketChannel getChannel() {
		return socket.getChannel();
	}

	public boolean hasData() {
		return socket.hasData();
	}

	public void processPeek() {
		processPeek(System.currentTimeMillis());
	}

	public void processPeek(long currentTime) {
		if (socket.hasData()) {
			int count = socket.peek(bufferData);
			onDataRead(bufferData, 0, count);
		} else {
			idle(currentTime);
		}
	}

	public String toString() {
		return "SimpleConnection[" + socket.toString() + "]";
	}
}
